import { Toast } from 'vant'
import userModule from './userInfo'
import router from '@/router'
import { BASE_URL_WS } from './baseUrl'

let socket = null

// 初始化websocket的连接
export const initWebSocket = () => {
  if (typeof WebSocket === 'undefined') {
    console.error('当前环境不支持WebSocket')
    return
  }
  const url = BASE_URL_WS.dev
  socket = new WebSocket(url)

  socket.onopen = () => {
    console.log('WebSocket连接成功')
    const token = localStorage.getItem('u_t')
    if (token) {
      const message = { type: 'LOGIN', token: token }
      socket.send(JSON.stringify(message))
    }
  }

  socket.onmessage = (event) => {
    const data = JSON.parse(event.data)
    switch (data.type) {
      case 'DUPLICATE_LOGIN':
        handleLoginResponse()
        break
    }
  }

  socket.onclose = () => {
    console.log('WebSocket连接关闭')
  }

  socket.onerror = (error) => {
    console.error('WebSocket发生错误：', error)
  }

  // 登陆处理
  function handleLoginResponse() {
    // 处理重复登录的情况
    Toast('账号在其他设备上登陆，如果不是本人操作，请修改密码')
    userModule.setUser(null)
    localStorage.removeItem('u_t')
    router.push('/login')
  }
}
// 发送消息
export const sendMessage = (message) => {
  // 如果是登录操作，尝试重新连接
  if (message.type === 'LOGIN') {
    socket.close()
    initWebSocket()
  }
  if (socket && socket.readyState === WebSocket.OPEN) {
    socket.send(JSON.stringify(message))
  } else {
    console.log('WebSocket连接未打开或已关闭')
  }
}
